package org.zjt.agent.runtime;

import com.sun.tools.attach.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Description:
 *
 *      运行时候运行agent中的agentmain
 *
 * @author juntao.zhang
 * Date: 2018-10-24 1:52 PM
 * @see
 */
public class RuntimeAttachAgentStart {

    public static void main(String[] args) throws IOException, AttachNotSupportedException{
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        List<VirtualMachineDescriptor> collect = list.stream().filter(item -> item.displayName().contains("compplication")).collect(Collectors.toList());

        VirtualMachine virtualMachine = VirtualMachine.attach(collect.get(0).id());
        try {
            virtualMachine.loadAgent("/java-agent-demo-0.0.1-SNAPSHOT.jar");

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            virtualMachine.detach();
        }
    }

}
